package net.piggy.config.security.filter;

import com.alibaba.fastjson.JSONObject;
import net.piggy.common.constant.ParameterConstant;
import net.piggy.common.util.general.ApplicationContextUtil;
import net.piggy.model.agg.SecurityUser;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class TokenVerifyFilter extends OncePerRequestFilter {
    private final SimpleGrantedAuthority simple = new SimpleGrantedAuthority("system:anonymous");
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if(token != null && !"".equals(token)){
            RedisTemplate<?,?> redisTemplate = (RedisTemplate<?, ?>) ApplicationContextUtil.getApplicationContext().getBean("redisTemplate");
            Object o = redisTemplate.opsForValue().get(ParameterConstant.TOKEN + token);
            if(o != null){
                SecurityUser user = JSONObject.parseObject(o.toString(), SecurityUser.class);
                UsernamePasswordAuthenticationToken username = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(username);
                filterChain.doFilter(request, response);
            }else{
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json;charset=UTF-8");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().println("{\"code\":401,\"message\":\"token失效，请重新登录\"}");
            }
        }
//        else{
//            ArrayList<SimpleGrantedAuthority> list = new ArrayList<>();
//            list.add(simple);
//            PreAuthenticatedAuthenticationToken pre = new PreAuthenticatedAuthenticationToken(null, null, list);
//            SecurityContextHolder.getContext().setAuthentication(pre);
//            filterChain.doFilter(request, response);
//        }
    }
}
